#include <iostream>
#include <string>
#include <cstdint>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "Thread.hpp"

using namespace ThreadModlue;

int sockfd = 0;
std::string server_ip;
uint16_t server_port;
pthread_t tid;

void Recv()
{
    while(1)
    {
        struct sockaddr_in peer;
        socklen_t len;
        char buff[10240];
        int m = recvfrom(sockfd, buff, sizeof(buff)-1, 0, (struct sockaddr*)&peer, &len);
        if(m > 0)
        {
            buff[m] = 0;
            std::cerr << buff << std::endl;
        }
    } 
}

void Send()
{
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    const std::string online = "i come!!";
    sendto(sockfd, online.c_str(), online.size(), 0, (struct sockaddr*)&server, sizeof(server));
    while(true)
    {
        std::string input;
        std::cout << "please enter: ";
        std::getline(std::cin, input);
        int n = sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr*)&server, sizeof(server));
        if(input == "quit")
        {
            pthread_cancel(tid);
            break;
        }
    }
}

int main(int args, char* argv[])
{
    if(args != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
    }
    server_ip = argv[1];
    server_port = std::stoi(argv[2]);

    // 创建套接字
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        return 2;
    }

    Thread recver(Recv);
    Thread sender(Send);

    recver.Start();
    sender.Start();

    tid = recver.Tid();

    recver.Join();
    sender.Join();

    return 0;
}